<template>
  <div ref="slRef" class="list-wrap" :style="listWrapStyle">
    <slot></slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      listWrapStyle: ''
    }
  },
  updated () {
    this.listWrapStyle = this.getListWrapStyle()
  },
  methods: {
    getListWrapStyle () {
      const parentEl = this.$refs.slRef?.parentNode
      if (!parentEl) return
      const childNodes = parentEl.childNodes
      const searchHeight = childNodes[0]?.offsetHeight ?? 0
      const elStyle = this.getElStyleNum(parentEl) // 父容器的样式对象
      const boxMaxHeight = elStyle('maxHeight') // 父容器最大高度
      const boxMinHeight =  elStyle('minHeight') // 父容器最小高度
      const boxPadding = elStyle('paddingTop') + elStyle('paddingBottom') // 父容器padding高度
      const boxBorder = elStyle('borderTop') + elStyle('borderBottom') // 父容器border高度
      const listMaxHeightStyle = `maxHeight:${boxMaxHeight - searchHeight - boxPadding - boxBorder}px;`
      const listMinHeightStyle = `minHeight:${boxMinHeight - searchHeight - boxPadding - boxBorder}px;`
      return listMaxHeightStyle + listMinHeightStyle
    },
    // 获取样式转换的数值
    getElStyleNum (parentEl) {
      return attrStyleName => {
        const attrStyle = document.defaultView.getComputedStyle(parentEl, null)[attrStyleName] ?? ''
        const attrNum = parseInt(attrStyle, 10)
        if (isNaN(attrNum)) return 0
        return attrNum
      }
    }
  }
}
</script>
<style lang="less" scoped>
.list-wrap {
  padding: 10px 20px;
  overflow: hidden;
  overflow-y: auto;
}
</style>
